package com.cavedroid;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;

public class Obstacles {
	
	public static final int MAX_NUMBER_OF_OBSTACLES = 5;
	
	public static final float HEIGHT = 1;
	
	public static final float DEPTH = 1;
	
	protected int DIMS;
	
	public float[] array;
	
	public int count = 0;
	
	protected int point = 0;	
	
	public CubeDrawer cube;
	
	public Obstacles(CubeDrawer cubeDrawer) {
		DIMS = 4;
		array = new float[MAX_NUMBER_OF_OBSTACLES*DIMS];
		cube = cubeDrawer;
	}
	
	public void drawShape(GL10 gl) {
		float x, y, z, width;
		int arrayIndex = 0;
		for (int i = 0; i < count; i++) {
			x = array[arrayIndex++];
			y = array[arrayIndex++];
			z = array[arrayIndex++];
			width = array[arrayIndex++];
			gl.glColor4f(1,0,1,0.5f);
			drawRect(gl, x, y, z, width);
		}
	}
	
	public void drawRect(GL10 gl, float x, float y, float z, float width) {
		gl.glPushMatrix();
		gl.glTranslatef(x, y, z);
		gl.glScalef(width, HEIGHT, DEPTH);
		cube.draw(gl);
		gl.glPopMatrix();
	}
	
	public void newObstacle(float x, float y, float z, float limit) {
		int index = point*DIMS;
		float offset = limit*((float)Math.random()*2-1)*0.5f;

		array[index++] = x;
		array[index++] = y + offset;
		array[index++] = z;
		array[index++] = (float)Math.sqrt(limit*limit - offset*offset)*2*0.8f;
		if (count < MAX_NUMBER_OF_OBSTACLES) {
			count++;
		}
		point++;
		point %= MAX_NUMBER_OF_OBSTACLES;
	}
	
	protected float getDistanceFromIndex(int index, float x, float y, float z) {
		return Geometry.distance2(y, z, array[index*DIMS+1], array[index*DIMS+2]);
	}
	
	public float getDistance(float x, float y, float z) {
		if (count > 0) {
			float current;
			float shortest = Float.MAX_VALUE;
			int index = 0;
			for (int i = 0; i < count; i++) {
				current = Math.abs(z-array[((point+i) % count)*DIMS+2]);
				if (current < shortest) {
					shortest = current;
					index = (point+i) % count;
				}
			}
			float distance = getDistanceFromIndex(index, x, y, z);
			
			if (z > array[index*DIMS+2]) {
				return distance-HEIGHT;
			} else {
				return distance;
			}
		}
		return Float.MAX_VALUE;
	}
}
